from django.contrib import admin
from django.utils.html import format_html
from django.utils import timezone
from datetime import timedelta
from .models import Category, Book, BorrowRecord, Reservation

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'description', 'created_at']
    search_fields = ['name']
    ordering = ['name']

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ['isbn', 'title', 'author', 'category', 'status', 'available_copies', 'total_copies', 'created_at']
    list_filter = ['status', 'category', 'created_at']
    search_fields = ['isbn', 'title', 'author', 'publisher']
    readonly_fields = ['available_copies', 'created_at', 'updated_at']
    fieldsets = (
        ('基本信息', {
            'fields': ('isbn', 'title', 'author', 'category', 'publisher', 'publish_date')
        }),
        ('详细信息', {
            'fields': ('description', 'total_copies', 'available_copies', 'location')
        }),
        ('状态信息', {
            'fields': ('status', 'created_at', 'updated_at')
        }),
    )
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('category')

@admin.register(BorrowRecord)
class BorrowRecordAdmin(admin.ModelAdmin):
    list_display = ['book', 'borrower', 'borrow_date', 'due_date', 'return_date', 'status', 'is_overdue_display']
    list_filter = ['status', 'borrow_date', 'due_date', 'return_date']
    search_fields = ['book__title', 'book__isbn', 'borrower__username']
    readonly_fields = ['borrow_date']
    date_hierarchy = 'borrow_date'
    
    def is_overdue_display(self, obj):
        if obj.is_overdue():
            return format_html('<span style="color: red;">逾期</span>')
        return format_html('<span style="color: green;">正常</span>')
    is_overdue_display.short_description = '逾期状态'
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('book', 'borrower')
    
    def save_model(self, request, obj, form, change):
        if not change:  # 新创建的借阅记录
            # 设置默认还书日期为30天后
            obj.due_date = timezone.now() + timedelta(days=30)
        super().save_model(request, obj, form, change)

@admin.register(Reservation)
class ReservationAdmin(admin.ModelAdmin):
    list_display = ['book', 'user', 'reservation_date', 'status']
    list_filter = ['status', 'reservation_date']
    search_fields = ['book__title', 'user__username']
    readonly_fields = ['reservation_date']
    
    def get_queryset(self, request):
        return super().get_queryset(request).select_related('book', 'user')
